<script setup lang="ts">

import { Modal } from 'ant-design-vue';
import { ColumnsType, TablePaginationConfig } from 'ant-design-vue/lib/table/Table';
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';

import router from '../app-router';
import { useWindowInnerSize } from '../shared/composables/general-omposable';
import AuthenticationService from '../shared/services/authentication-service';
import User from './user';
import UserService from './user-service';

const EditUser = defineAsyncComponent(() => import('./EditUser.vue'));
const tableSize = useWindowInnerSize({ heightOffset: 200 });
const tableScrollSize = useWindowInnerSize({ heightOffset: 240 });

// Union type. Added [key] to [User] type. This is for ant data table component.
type UserType = User & { key: string };

const columns: ColumnsType<UserType> = [
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'left',
  },
  {
    title: '头像',
    dataIndex: 'avatarUrl',
    key: 'avatarUrl',
    width: 100,
    // customCell: (record, rowIndex, column) => vnode,
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 130,
  },
  {
    title: '昵称',
    dataIndex: 'fullName',
    key: 'fullName',
    ellipsis: true,
  },
];

const data = ref<UserType[]>([]);
const loading = ref<boolean>(false);
const rowSelection = ref<any>(undefined);
const selectedIds = ref<string[]>([]);
const open = ref<boolean>(false);

const pagination = reactive<TablePaginationConfig>({
  current: 1,
  pageSize: 20,
  total: 0,
});

onMounted(() => {
  query();
});

async function query(): Promise<void> {
  // Enables data table loading status.
  loading.value = true;

  UserService.queryAccountGroupUsers(pagination.pageSize!, pagination.current!).then((res) => {
    // Queries data and converts the union type.
    data.value = res.map((p) => {
      return {
        ...p,
        key: p.id,
      };
    }) as UserType[];

    // TODO: Uses real number returned from api.
    pagination.total = 200;
  }).finally(() => loading.value = false);
}

function onClickSetShowRowSelection(): void {
  if (rowSelection.value) {
    rowSelection.value = null;
  } else {
    rowSelection.value = {
      onChange: (selectedRowKeys: string[], selectedRows: UserType[]) => {
        selectedIds.value = selectedRowKeys.map((p) => p.toString());
      },
      getCheckboxProps: (record: UserType) => ({
        disabled: record.isAccountGroupCreator || record.id === AuthenticationService.currentUser?.id, // Column configuration not to be checked
        // name: record.name,
      }),
    };
  }
}

function onChange(newPagination: TablePaginationConfig): void {
  pagination.pageSize = newPagination.pageSize;
  pagination.current = newPagination.current;
  query();
}

function reload(): void {
  pagination.current = 1;
  query();
}

function onOk(): void {
  reload();
  open.value = false;
}

function deleteData(): void {
  Modal.confirm({
    title: '确认删除？',
    content: `删除所选 ${selectedIds.value.length} 项数据吗？`,
    async onOk() {
      await UserService.delete(selectedIds.value);
      reload();
    },
  });
}
</script>

<template>
  <div>
    <a-table :loading="loading" :columns="columns" :data-source="data" :pagination="pagination"
      :row-selection="rowSelection" bordered :scroll="{ y: tableScrollSize.height }" @change="onChange"
      :style="{ height: `${tableSize.height}px` }">
      <template #title="currentPageData">
        <a-space>
          <a-button type="primary" @click="open = true">添加</a-button>
          <a-button @click="onClickSetShowRowSelection">{{ rowSelection ? '取消' : '选择' }}</a-button>
          <a-button v-if="rowSelection" @click="deleteData" :disabled="selectedIds.length === 0">删除</a-button>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'avatarUrl'">
          <a-avatar :src="record.avatarUrl" />
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button @click="router.push(`/user/detail/${record.id}`)">详情</a-button>
        </template>
      </template>
    </a-table>
    <a-modal title="添加用户" v-model:open="open" :footer="null">
      <EditUser @ok="onOk" @cancel="() => open = false" />
    </a-modal>
  </div>
</template>

<style scoped></style>